package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//线程池版本回显服务器
public class TcpEchoServer3 {
    //clientSocket就是内场的服务人员，每个客户端都会自动分配一个
    //serverSocket只有一个，是负责在外场拉客的人
    private ServerSocket serverSocket = null;

    public TcpEchoServer3(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        //创建一个线程池，没有参数就是动态创建，没有用的了就增加线程池的数量
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnextion(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }
    //这个处理请求就是具体的方法，先把数据读入，处理完请求在把数据反馈给客户端
    private void processConnextion(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线！\n", clientSocket.getInetAddress(),
                clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1.读取请求
                if (!scanner.hasNext()) {
                    //printf是按照格式进行输出，%s就是打印字符串
                    System.out.printf("[%s:%d] 客户端下线！\n", clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                //没有读到结尾，需要一直读取数据
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                printWriter.println(response);//把这个按照字符串进行打印
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s, resp:%s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }

    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer3 tcpEchoServer3 = new TcpEchoServer3(9000);
        tcpEchoServer3.start();
    }
}
